#!/bin/bash 

#题目：有log文件（ipHttpData），请打印出独立IP，并统计独立IP数，（分别使用python和shell），检测异常ip（1分钟内访问超过30次）

#awk -f '{ printf "%s %s \n", $1,$4 }' ipHttpData.ipHttpData


printf "独立IP包括："
count=0   #独立IP数目
exist=0   #判定IP是否存在的变量
zero=0     
addcount=1   #递增变量
ip_address=()   #存放IP地址的数组
time_str=()
str=()      #存放IP对应的访问数量的数组
unnormal=30 

while read line 
do
    cutline=`echo $line |awk -F' ' '{print $1}'`  
    if [ $count -eq $zero ] 
    then
        ip_address[count]=$cutline 
        str[count]=1
        count=`expr $count + $addcount`
    else
        #cutline=`echo $line |awk -F' ' '{print $1}'`
        for((var=0;var<$count;var++))
        do
            #cutline=`echo $line |awk -F' ' '{print $1}'`
            if [ "$cutline"x = ${ip_address[var]}x ]
            then  
                exist=1
                str[var]=`expr ${str[var]} + $exist`
                break
            fi
            #if [ $exist -eq $zero ]
            #then
                #ip_address[count]=`echo $line |awk -F' ' '{print $1}'`
                #str[count]=1
                #count=`expr $count + $addcount`
            #else
                #exist=0
            #fi
        done
        if [ $exist -eq $zero ]
        then         
            ip_address[count]=$cutline
            str[count]=1
            count=`expr $count + $addcount`
        else
            exist=0
        fi
    fi
done < ipHttpData.ipHttpData

for number in ${ip_address[@]}
do 
    printf "%s  "  $number
done
printf "\n独立IP数一共有 %d 个 \n" ${count}
printf "异常IP如下：" 

for((nn=0;nn<$count;nn++))
do
    if [ ${str[nn]} -gt 30 ]
    then  
       time_count=0
       while read line 
       do  
           cutline=`echo $line |awk -F' ' '{print $1}'`
           if [ "$cutline"x = ${ip_address[nn]}x ]
           then
               cut_time=`echo $line |awk -F' ' '{print $4}'`
               iptime=${cut_time:1} 
               #将iptime的第一个：字符替换为空格 
               iptime=${iptime/":"/" "} 
               time_str[time_count]=$iptime
               time_count=`expr $time_count + $addcount`
           else
               continue 
           fi 
       done < ipHttpData.ipHttpData
       f=`expr $time_count - $unnormal`
       for((mm=0;mm<f;mm++))
       do 
           dec=$(( date2 - date1 ))
           if [ $dec -lt 60 ]
           then
              printf "%s  " ${ip_address[nn]}
              break  
           else
               continue
           fi 
       done 
    else
        continue 
    fi  
done 
printf "\n"




